# coding:utf-8
import os
from os import path
from PIL import Image, ImageDraw

class ImagePre:
    # src 原始图片路径
    # dst 降噪后的目标图片路径
    def __init__(self,src,dst) -> None:
        self.src=src
        self.dst=dst
        self.t2val={}
    
    # G: Integer 图像二值化阀值
    def twoValue(self,image,G):
        for y in range(0, image.size[1]):
            for x in range(0, image.size[0]):
                g = image.getpixel((x, y))
                if g > G:
                    self.t2val[(x, y)] = 1
                else:
                    self.t2val[(x, y)] = 0

    def clearNoise(self,image,N,Z):
        # 根据一个点A的RGB值，与周围的8个点的RBG值比较，设定一个值N（0 <N <8），当A的RGB值与周围8个点的RGB相等数小于N时，此点为噪点        
        # N: Integer 降噪率 0 <N <8
        # Z: Integer 降噪次数
        # 输出
        #  0：降噪成功
        #  1：降噪失败

        for i in range(0, Z):
            self.t2val[(0, 0)] = 1
            self.t2val[(image.size[0] - 1, image.size[1] - 1)] = 1

            for x in range(1, image.size[0] - 1):
                for y in range(1, image.size[1] - 1):
                    nearDots = 0
                    L = self.t2val[(x, y)]
                    if L == self.t2val[(x - 1, y - 1)]:
                        nearDots += 1
                    if L == self.t2val[(x - 1, y)]:
                        nearDots += 1
                    if L == self.t2val[(x - 1, y + 1)]:
                        nearDots += 1
                    if L == self.t2val[(x, y - 1)]:
                        nearDots += 1
                    if L == self.t2val[(x, y + 1)]:
                        nearDots += 1
                    if L == self.t2val[(x + 1, y - 1)]:
                        nearDots += 1
                    if L == self.t2val[(x + 1, y)]:
                        nearDots += 1
                    if L == self.t2val[(x + 1, y + 1)]:
                        nearDots += 1

                    if nearDots < N:
                        self.t2val[(x, y)] = 1

    # 找出图片中第一个像素点的横坐标。便于切割
    def findFirstPix(self,image):
        result=[]
        for y in range(0, image.size[1]):
            for x in range(0, image.size[0]):
                g = image.getpixel((x, y))
                if g < 255:
                    result.append(x)
                    break
        return min(result)

    def split_img(self,image,index):#原来
        picDir=path.join(path.dirname(image),'..','pic')
        symboldir=path.join(path.dirname(image),'..','picSymbol')

        
        image1 = Image.open(image).crop((5, 5, 20, 30))
        image1.save(path.join(picDir,str(index)+'.png'))

        # image2 = Image.open(image).crop((20, 5, 30, 30))
        image2 = Image.open(image).crop((28, 5, 38, 30))
        image2.save(path.join(symboldir,str(index//2)+'.png'))
        
        image3 = Image.open(image).crop((35, 5, 50, 30))
        if(self.findFirstPix(image3)>2):
            image3=Image.open(image).crop((41, 5, 56, 30))   
        else:
            #a+b
            image3=Image.open(image).crop((49, 5, 64, 30))      

        image3.save(path.join(picDir,str(index+1)+'.png'))

    def saveImage(self,filename,size):
        image = Image.new("1", size)
        draw = ImageDraw.Draw(image)
        for x in range(0, size[0]):
            for y in range(0, size[1]):
                draw.point((x, y), self.t2val[(x, y)])
        image.save(filename)
        

    def main(self):
        list=os.listdir(self.src)
        for i,f in enumerate(list):
            source=os.path.join(self.src,f)
            target=os.path.join(self.dst,f)
            image=Image.open(source).convert('L')
            self.twoValue(image,100)
            self.clearNoise(image,2,1)
            self.saveImage(target,image.size)
            self.split_img(target,2*i)


if __name__=='__main__':
    targetPath = r'D:\yangqin\noiseImg'
    originPath=r'D:\yangqin\sourceImg'
    imgpre=ImagePre(originPath,targetPath)
    imgpre.main()